#!/usr/bin/env python3
"""
LangChain智能助手安装脚本

这个脚本帮助用户快速设置和配置LangChain学习环境。
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path

def print_step(step_num, description):
    """打印安装步骤"""
    print(f"\n{'='*50}")
    print(f"步骤 {step_num}: {description}")
    print('='*50)

def check_python_version():
    """检查Python版本"""
    print_step(1, "检查Python版本")
    
    version = sys.version_info
    print(f"当前Python版本: {version.major}.{version.minor}.{version.micro}")
    
    if version.major < 3 or (version.major == 3 and version.minor < 9):
        print("❌ 错误: 需要Python 3.9或更高版本")
        return False
    
    print("✅ Python版本检查通过")
    return True

def check_venv():
    """检查虚拟环境"""
    print_step(2, "检查虚拟环境")
    
    if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
        print("✅ 已在虚拟环境中")
        return True
    else:
        print("⚠️  警告: 未检测到虚拟环境")
        print("建议在虚拟环境中运行此项目")
        
        response = input("是否继续安装? (y/N): ").lower().strip()
        return response == 'y'

def install_dependencies():
    """安装依赖"""
    print_step(3, "安装Python依赖")
    
    try:
        print("正在安装依赖包...")
        subprocess.check_call([
            sys.executable, "-m", "pip", "install", "-r", "requirements.txt"
        ])
        print("✅ 依赖安装完成")
        return True
    
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        return False

def setup_environment():
    """设置环境变量"""
    print_step(4, "设置环境变量")
    
    env_file = Path(".env")
    env_example = Path(".env.example")
    
    if env_file.exists():
        print("✅ .env文件已存在")
        return True
    
    if env_example.exists():
        try:
            shutil.copy(env_example, env_file)
            print("✅ 已创建.env文件")
            print("⚠️  请编辑.env文件，添加您的API密钥")
            return True
        except Exception as e:
            print(f"❌ 创建.env文件失败: {e}")
            return False
    else:
        print("❌ 未找到.env.example文件")
        return False

def create_directories():
    """创建必要的目录"""
    print_step(5, "创建项目目录")
    
    directories = [
        "chroma_db",
        "logs",
        "exports"
    ]
    
    for directory in directories:
        Path(directory).mkdir(exist_ok=True)
        print(f"✅ 创建目录: {directory}")
    
    return True

def verify_installation():
    """验证安装"""
    print_step(6, "验证安装")
    
    try:
        # 测试导入主要模块
        import langchain
        import langchain_openai
        import chromadb
        import rich
        
        print("✅ 核心模块导入成功")
        
        # 检查配置
        from config.settings import settings
        print("✅ 配置模块加载成功")
        
        return True
    
    except ImportError as e:
        print(f"❌ 模块导入失败: {e}")
        return False
    
    except Exception as e:
        print(f"❌ 验证失败: {e}")
        return False

def print_next_steps():
    """打印后续步骤"""
    print("\n" + "="*50)
    print("🎉 安装完成！")
    print("="*50)
    
    print("\n📋 后续步骤:")
    print("1. 编辑 .env 文件，添加您的 OpenAI API 密钥:")
    print("   OPENAI_API_KEY=your_api_key_here")
    print("\n2. 运行主程序:")
    print("   python main.py")
    print("\n3. 查看示例:")
    print("   python examples/basic_chat.py")
    print("\n4. 阅读文档:")
    print("   README.md")
    
    print("\n🔗 有用的链接:")
    print("- OpenAI API: https://platform.openai.com/api-keys")
    print("- LangChain文档: https://python.langchain.com/")
    print("- 项目GitHub: https://github.com/langchain-ai/langchain")

def main():
    """主安装函数"""
    print("🦜🔗 LangChain智能助手安装程序")
    print("欢迎使用LangChain学习项目！")
    
    # 执行安装步骤
    steps = [
        check_python_version,
        check_venv,
        install_dependencies,
        setup_environment,
        create_directories,
        verify_installation
    ]
    
    for step in steps:
        if not step():
            print(f"\n❌ 安装失败，请检查错误信息")
            sys.exit(1)
    
    print_next_steps()

if __name__ == "__main__":
    main() 